package com.tianxiao.faas.application.web.corner;

import com.google.common.collect.Lists;
import com.tianxiao.faas.api.param.corner.BasePageParam;
import com.tianxiao.faas.api.param.corner.BazaarJoinPageParam;
import com.tianxiao.faas.api.param.corner.BazaarResult;
import com.tianxiao.faas.api.param.corner.ShopResult;
import com.tianxiao.faas.api.param.corner.UserInfoResult;
import com.tianxiao.faas.api.param.corner.UserResult;
import com.tianxiao.faas.application.aop.AuthenticationContextHolder;
import com.tianxiao.faas.biz.service.corner.ActivityService;
import com.tianxiao.faas.biz.service.corner.ShopService;
import com.tianxiao.faas.common.access.Access;
import com.tianxiao.faas.common.result.Result;
import com.tianxiao.faas.common.util.PageUtils;
import com.tianxiao.faas.mapper.dao.ActivityApplyModelMapper;
import com.tianxiao.faas.mapper.dao.ConcernModelMapper;
import com.tianxiao.faas.mapper.dao.FootPrintModelMapper;
import com.tianxiao.faas.mapper.dao.UsersModelMapper;
import com.tianxiao.faas.mapper.model.ConcernModel;
import com.tianxiao.faas.mapper.model.ConcernModelExample;
import com.tianxiao.faas.mapper.model.ShopModel;
import com.tianxiao.faas.mapper.model.UsersModel;
import com.tianxiao.faas.mapper.model.UsersModelExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/user")
public class UserController {
    @Resource
    private UsersModelMapper usersModelMapper;
    @Resource
    private ShopService shopService;
    @Resource
    private ConcernModelMapper concernModelMapper;
    @Resource
    private FootPrintModelMapper footPrintModelMapper;
    @Resource
    private ActivityApplyModelMapper activityApplyModelMapper;
    @Resource
    private ActivityService activityService;

    @RequestMapping(value = "/get")
    @Access
    public Result<UserResult> get() {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        UsersModel usersModel = usersModelMapper.selectByPrimaryKey(userId);
        ShopModel shopModel = shopService.getByUserId(userId);
        UserResult userResult = new UserResult();
        userResult.setAvatar(usersModel.getImg());
        userResult.setName(usersModel.getName());
        userResult.setId(usersModel.getId());
        Integer concernCount = concernModelMapper.countByUserId(userId);
        userResult.setConcernCount(concernCount == null ? 0 : concernCount);
        Integer footprintCount = footPrintModelMapper.countByUserId(userId);
        userResult.setFootprintCount(footprintCount);
        if (shopModel != null) {
            userResult.setShopId(shopModel.getId());
            userResult.setIsShop(true);
            Integer integer = activityApplyModelMapper.countByShopId(shopModel.getId(), 1);
            userResult.setBazaarCount(integer == null ? 0 : integer);
            Integer fansCount = concernModelMapper.countByShopId(shopModel.getId());
            userResult.setFansCount(fansCount == null ? 0 : fansCount);
        }
        return Result.builder().data(userResult).success(true);
    }

    @RequestMapping(value = "/update")
    @Access
    public Result<Boolean> update(@RequestBody UserResult param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        UsersModel usersModel = new UsersModel();
        usersModel.setId(userId);
        usersModel.setName(param.getName());
        usersModel.setImg(param.getAvatar());
        String mobile = param.getMobile();
        if (StringUtils.isNotEmpty(mobile) && StringUtils.isNumericSpace(mobile)) {
            usersModel.setMobile(mobile);
        }
        usersModel.setUpdated(System.currentTimeMillis());
        usersModelMapper.updateByPrimaryKeySelective(usersModel);
        return Result.builder().data(true).success(true);
    }

    @RequestMapping(value = "/concern/list")
    @Access
    public Result<List<ShopResult>> listConcern(@RequestBody BasePageParam param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        Double latitude = param.getLatitude();
        Double longitude = param.getLongitude();
        List<Long> list = concernModelMapper.list(userId, PageUtils.getOffset(page, pageSize), param.getPageSize());
        Integer count = concernModelMapper.countByUserId(userId);
        count = count == null ? 0 : count;
        List<ShopResult> data = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            data = shopService.list(list, latitude, longitude);
        }
        Result result = Result.builder().data(data)
                .success(true).pageNo(page).pageSize(pageSize).totalCount(count)
                .totalPage();
        return result;
    }

    @RequestMapping(value = "/footprint/list")
    @Access
    public Result<List<ShopResult>> listFootprint(@RequestBody BasePageParam param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        Double latitude = param.getLatitude();
        Double longitude = param.getLongitude();
        List<Long> list = footPrintModelMapper.list(userId, PageUtils.getOffset(page, pageSize), param.getPageSize());
        Integer count = footPrintModelMapper.countByUserId(userId);
        count = count == null ? 0 : count;
        List<ShopResult> data = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            data = shopService.list(list, latitude, longitude);
        }
        Result result = Result.builder().data(data)
                .success(true).pageNo(page).pageSize(pageSize).totalCount(count)
                .totalPage();
        return result;
    }

    @RequestMapping(value = "/concern/create")
    @Access
    public Result<Boolean> concernCreate(@RequestParam("id") Long id) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel byId = shopService.getById(id);
        if (byId == null) {
            return Result.builder().success(false).msg("关注的店铺不存在哦");
        }
        ConcernModelExample example = new ConcernModelExample();
        example.createCriteria().andUserIdEqualTo(userId).andShopIdEqualTo(id);
        List<ConcernModel> concernModels = concernModelMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(concernModels)) {
            ConcernModel concernModel = concernModels.get(0);
            ConcernModel concernModel1 = new ConcernModel();
            concernModel1.setId(concernModel.getId());
            concernModel1.setDeleted(0);
            concernModelMapper.updateByPrimaryKeySelective(concernModel1);
            return Result.builder().data(true).success(true);
        }

        ConcernModel concernModel = new ConcernModel();
        concernModel.setShopId(id);
        concernModel.setUserId(userId);
        long currentTimeMillis = System.currentTimeMillis();
        concernModel.setCreated(currentTimeMillis);
        concernModel.setUpdated(currentTimeMillis);
        concernModel.setDeleted(0);
        concernModelMapper.insertSelective(concernModel);
        return Result.builder().data(true).success(true);
    }

    @RequestMapping(value = "/concern/cancel")
    @Access
    public Result<Boolean> concernCancel(@RequestParam("id") Long id) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getById(id);
        if (shop == null) {
            return Result.builder().msg("店铺不存在").success(true);
        }
        ConcernModelExample example = new ConcernModelExample();
        example.createCriteria().andUserIdEqualTo(userId).andShopIdEqualTo(id);
        List<ConcernModel> concernModels = concernModelMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(concernModels)) {
            ConcernModel concernModel = concernModels.get(0);
            ConcernModel concernModel1 = new ConcernModel();
            concernModel1.setId(concernModel.getId());
            concernModel1.setDeleted(1);
            concernModelMapper.updateByPrimaryKeySelective(concernModel1);
            return Result.builder().data(true).success(true);
        }
        return Result.builder().data(true).success(true);
    }

    @RequestMapping(value = "/fans/list")
    @Access
    public Result<List<UserInfoResult>> listFans(@RequestBody BasePageParam param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getByUserId(userId);
        if (shop == null) {
            return Result.builder().msg("您还未开店，还没有粉丝").success(true);
        }
        Long id = shop.getId();
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        List<Long> userIds = concernModelMapper.listByShopId(id, PageUtils.getOffset(page, pageSize), pageSize);
        if (CollectionUtils.isEmpty(userIds)) {
            return Result.builder().data(Lists.newArrayList()).pageNo(page).pageSize(pageSize).success(true);
        }
        UsersModelExample example = new UsersModelExample();
        example.createCriteria().andIdIn(userIds);
        List<UsersModel> usersModels = usersModelMapper.selectByExample(example);
        List<ShopResult> shopResults = shopService.listByUserIds(userIds);
        Map<Long, ShopResult> shopResultMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(shopResults)) {
            shopResultMap = shopResults.stream().collect(Collectors.toMap(ShopResult::getUserId, s -> s));
        }
        List<UserInfoResult> data = new ArrayList<>();
        for (UsersModel user : usersModels) {
            UserInfoResult infoResult = new UserInfoResult();
            infoResult.setAvatar(user.getImg());
            infoResult.setId(user.getId());
            infoResult.setName(user.getName());
            ShopResult shopResult = shopResultMap.get(user.getId());
            if (shopResult != null) {
                infoResult.setFansCount(concernModelMapper.countByShopId(shopResult.getId()));
                Long shopId = shopResult.getId();
                infoResult.setShopId(shopId);
                Integer integer = concernModelMapper.countByShopIdAndUserId(shopId, userId);
                integer = integer == null ? 0 : integer;
                infoResult.setFriend((integer <= 0) ? false : true);
            }
            data.add(infoResult);
        }
        Integer integer = concernModelMapper.countByShopId(id);
        integer = integer == null ? 0 : integer;
        return Result.builder().data(data).pageNo(page).pageSize(pageSize).totalCount(integer)
                .totalPage().success(true);
    }

    @RequestMapping(value = "/bazaar/joinList")
    @Access
    public Result<List<BazaarResult>> joinList(@RequestBody BazaarJoinPageParam param) {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        ShopModel shop = shopService.getByUserId(userId);
        if (shop == null) {
            return Result.builder().msg("您还未开店").success(true);
        }
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        List<BazaarResult> bazaarResults = activityService.listJoinBazaar(userId, param.getPage(), param.getPageSize(), param.getStatus());
        Integer integer = activityApplyModelMapper.countByShopId(shop.getId(), param.getStatus());
        activityService.checkJoined(bazaarResults, userId);
        return Result.builder().data(bazaarResults).pageNo(page).pageSize(pageSize).totalCount(integer)
                .totalPage().success(true);
    }

    @RequestMapping(value = "/bazaar/list")
    @Access
    public Result<List<BazaarResult>> list() {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        List<BazaarResult> bazaarResults = activityService.listCanJoinBazaar(userId);
        activityService.checkJoined(bazaarResults, userId);
        return Result.builder().data(bazaarResults).success(true);
    }

    @RequestMapping(value = "/bazaar/success/list")
    @Access
    public Result<List<BazaarResult>> successList() {
        Long userId = AuthenticationContextHolder.currentContext().getUserId();
        List<BazaarResult> bazaarResults = activityService.listCanJoinBazaar(userId);
        activityService.checkJoined(bazaarResults, userId);
        return Result.builder().data(bazaarResults).success(true);
    }
}
